package com.mitac.mcd.cs.mobiletracking.socketserver.util;

import java.util.List;

import com.mitac.mcd.cs.mobiletracking.socketserver.HealthCheck;
import com.mitac.mcd.cs.mobiletracking.socketserver.MobileServer;
import com.mitac.mcd.cs.mobiletracking.socketserver.bean.NotificationMarkBean;

public class CheckReNotification extends Thread {

	String uuid = null;
	String ID = null;
	int badge;
	int type;
	int userId;
	int deviceType;
	String clientAddress;
	private boolean _run = true;
	
	public CheckReNotification(String uuid,String ID,int badge,int type, int userId, int deviceType, String clientAddress) {
        this.uuid = uuid;
        this.ID = ID;
        this.badge = badge;
        this.type = type;
        this.userId = userId;
        this.deviceType = deviceType;
        this.clientAddress = clientAddress;
        this.start();
    }
	
	public void stopThread() {
        this._run = false;
        BusinessUtil.aLogger.info(uuid+" CheckReNotification thread已经停止...");
    }
	
	public void run() {
		BusinessUtil.aLogger.info("新开一个CheckReNotification线程...");
		int count = 0;//发送成功才会启动check renotification thread，所以已经有一次
		while(this._run){
			try {
				Thread.sleep(MobileServer.notificationToClientDelayTime*1000);
			} catch (InterruptedException e) {
				BusinessUtil.aLogger.info(uuid+"对应的CheckReNotification线程sleep异常:"+e);
			}
			//check resend time
			if (count>=MobileServer.notificationToClientResendTime){
				String note = uuid+"对应的CheckReNotification线程已经重试发送notification"+MobileServer.notificationToClientResendTime+"次，终止线程，记录发送失败...";
				BusinessUtil.logException(uuid, userId, deviceType, clientAddress, "E013",note);
				//log notification detail to db
				BusinessUtil.logNotificationDetail(ID, uuid, "E013", count,"FAIL");
				BusinessUtil.aLogger.info(note);
				stopThread();
			}
			if(this._run){
				if(MobileServer.healthCheckList.containsKey(uuid)){
					HealthCheck _hc = MobileServer.healthCheckList.get(uuid);
					List<NotificationMarkBean> notificationList = _hc.getNotificationList();
					for(NotificationMarkBean bean:notificationList){
						if (bean.getId().equals(ID)) {
							if (!bean.isReceiveFlag()){//current fail
								BusinessUtil.sendNotificationToClient(uuid, ID, badge, type, userId, deviceType, clientAddress);
								count ++;
							}else{//success
								//log notification detail to db
								BusinessUtil.logNotificationDetail(ID, uuid, null, count, "SUCCESS");
								stopThread();
							}
						}
					}
				}
			}
			
		}
	}
}
